package com.jcw.kqxt.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jcw.kqxt.constants.Constant;
import com.jcw.kqxt.domain.Attendance;
import com.jcw.kqxt.dto.AttendanceDto;
import com.jcw.kqxt.exception.MyException;
import com.jcw.kqxt.mapper.AttendanceMapper;
import com.jcw.kqxt.mapper.DeptMapper;
import com.jcw.kqxt.result.JSONResult;
import com.jcw.kqxt.service.IAttendanceService;
import com.jcw.kqxt.util.DateUtils;
import com.jcw.kqxt.vo.AttendanceVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author qinhui
 * @since 2022-02-25
 */
@Service
public class AttendanceServiceImpl extends ServiceImpl<AttendanceMapper, Attendance> implements IAttendanceService {

    //考勤规则
    private static final String TYPE = "1";

    //时段 0 上午
    private static final int AM =0;

    //时段 1 下午
    private static final int PM =1;

    @Autowired
    private AttendanceMapper attendanceMapper;

    @Autowired
    private DeptMapper deptMapper;

    @Override
    public JSONResult findAttendanceByDto(AttendanceDto dto) {
        if(dataValidation(dto)){
            return JSONResult.error("数据错误!");
        }
        //查询对应参数的数据
        Attendance attendance =  attendanceMapper.selectOneModel(dto);
        //查询考勤天数
        Wrapper<Attendance> wrapper = new EntityWrapper<>();
        wrapper.eq("attendance_status", Constant.ATTENDANCE)
                .eq("user_name", dto.getName());
        Integer count = attendanceMapper.selectCount(wrapper);
        //考勤天数
        int attendanceDays = count % 2 == 0 ? count / 2 : count / 2 + 1;
        //获取当月天数
        int daysOfMonth = DateUtils.getDaysOfMonth(dto.getDate());
        return JSONResult.success(new AttendanceVo(attendance,attendanceDays,daysOfMonth));
    }

    @Override
    public JSONResult findAll(AttendanceDto dto) {
        //数据校验
        String deptName = dto.getDeptName();
        String date = dto.getDate();
        if(StringUtils.isAnyBlank(deptName,date)){
            throw new MyException("数据错误!");
        }
        //查询部门id
        Long deptId = deptMapper.selectDeptIdByDeptName(deptName);
        //根据条件查询考勤集合
        List<Attendance> list = attendanceMapper.selectListByDeptIdAndDate(deptId,date);
        //查询考勤天数
        Wrapper<Attendance> wrapper = new EntityWrapper<>();
        wrapper.eq("attendance_status", Constant.ATTENDANCE);
        Integer count = attendanceMapper.selectCount(wrapper);
        //考勤天数
        int attendanceDays = count % 2 == 0 ? count / 2 : count / 2 + 1;
        int daysOfMonth = DateUtils.getDaysOfMonth(date);
        //封装 返回给前端
        AttendanceVo attendanceVo = new AttendanceVo(list, attendanceDays,daysOfMonth);

        return JSONResult.success(attendanceVo);
    }

    @Override
    @Transactional
    public JSONResult oneKeyOperation(AttendanceDto dto) {
        if(dataValidation(dto)){
            return JSONResult.error("数据错误!");
        }
        //user_id
        Long userId = attendanceMapper.selectUserIdByUserName(dto.getName());
        //dept_id
        Integer deptId = attendanceMapper.selectDeptIdByDeptNameAndName(dto.getDeptName(),dto.getName());
        //获取传入的日期月份的天数
        int days = DateUtils.getDaysOfMonth(dto.getDate());
        //根据当月天数查询考勤 如1日 i=1 2 i=2 ...
        //1. 查询 null 新增上午 和 下午
        //2 查询1条数据 新增上午/下午 根据查询结果新增
        //3 查询2条数据 不操作
        for (int i = 1; i <= days; i++) {
            String date;
            if(i>=1&&i<=9){
                date = dto.getDate()+"-0"+i;
            }else {
                date= dto.getDate()+"-"+i;
            }
            List<Attendance> attendanceList = attendanceMapper.selectListByDeptIdAndNameAndDate(deptId,dto.getName(),date);
            Attendance attendance;
            if(attendanceList==null||attendanceList.size()==0){
                attendance = getAttendance(userId, dto, deptId,null,date);
                Attendance targetAttendance = new Attendance();
                BeanUtil.copyProperties(attendance,targetAttendance,false);
                targetAttendance.setTimeInterval(PM);
                super.insert(targetAttendance);
            }
            else if(attendanceList.size()==1){
                attendance = getAttendance(userId,dto,deptId,attendanceList.get(0),date);
                int timeInterval = attendance.getTimeInterval()==AM?PM:AM;
                attendance.setTimeInterval(timeInterval);
            }else {
                continue;
            }
            super.insert(attendance);
        }
        return JSONResult.success();
    }

    /**
     * 数据校验
     * @param dto
     * @return
     * true 数据错误 false 正常
     */
    private boolean dataValidation(AttendanceDto dto){
        String date = dto.getDate();
        String name = dto.getName();
        String deptName = dto.getDeptName();
        if(StringUtils.isAnyBlank(name,deptName,date)){
            return true;
        }
        return false;
    }

    private Attendance getAttendance(Long userId,AttendanceDto dto,Integer deptId,Attendance nowAttendance,String date){
        Attendance attendance = new Attendance();
        //user_id
        attendance.setUserId(userId);
        //user_name
        attendance.setUserName(dto.getName());
        //attendance_status
        attendance.setAttendanceStatus(dto.getAttendanceStatus());

        //校验nowAttendance 默认上午
        Integer timeInterval = nowAttendance == null ? AM : nowAttendance.getTimeInterval();
        attendance.setTimeInterval(timeInterval);
        //dept_id
        attendance.setDeptId(deptId);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = new Date();
        try {
             parse = format.parse(date);
        }catch (ParseException e){
            e.printStackTrace();
        }
        //create_time
        attendance.setCreateTime(parse);
        //update_time null就可以
        //type
        attendance.setType(TYPE);
        //duration 时长 null
        //date 迟到日期 null
        return attendance;
    }
}
